<template>
    <div class="bigContent">   
      <div class="contentMain">
        <img ref="imageVal" :src="imgUrl" class="imgClass"/>
        <div class="bigImgPD">
          <span class="reset-btn" type="text" @click="close" >取消</span>
          <van-button class="bigImgBtn" type="primary" @click="sureSave">确认</van-button>
      </div>
      </div>
    </div>  
</template>

<script setup>
import {defineProps,defineEmits,reactive,onMounted,ref} from 'vue';
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
const props = defineProps({
  imgUrl:{
    type:String,
    default:''
  }
})

//emit 返回值
const emit = defineEmits(['success','close']);
const imageVal = ref(null); //裁剪图片容器区域
const  cropperObj= reactive({
  afterImg:'', //裁剪后的图片
  myCropper:null //进行裁剪
})
onMounted(()=>{
  cropperObj.myCropper = new Cropper(imageVal.value, {
    viewMode: 2, //裁剪框不能超出图片的范围     
    outputType:'jpg', 
    fixed:true,
    dragMode: 'move', //拖拽图片模式 move 图片可移动 
    guides:true, //是否显示裁剪框的虚线  
    center:true, //是否显示裁剪框中间的 ‘+’ 指示器 默认true
    aspectRatio:1, //设置裁剪框为固定的宽高比
    background: false,//是否在容器内显示网格状的背景 默认true
    cropBoxMovable: true, //是否可以拖拽裁剪框 默认true
    cropBoxResizable:true, // 是否可以改变裁剪框的尺寸
    autoCrop:true, //默认生成截图框 
    fixedBox:true, //固定截图框大小 不允许改变
    autoCropArea: 0.8, //设置裁剪区域占图片的大小 值为 0-1 默认 0.8 表示 80%的区域
    zoomOnWheel: true,//鼠标滑轮是否可以放大缩小图片
    fixedNumber:[1,1], //截图框比例
    canMoveBox:true,  //截图框拖动，true 可以拖动
    canMove:true,  //上传图片是否可以拖动
    centerBox:false, //截图框是否被限制在图片里
    infoTure:true, //看到的裁图框宽高
  })
})

function close(){
   emit('close')
}

const sureSave = () =>{
  let list = []
  cropperObj.afterImg = cropperObj.myCropper.getCroppedCanvas({
    imageSmoothingQuality: 'high'
  }).toBlob(async(blob) => {
    const file = new File([blob], "头像.png", { type: "image/png" })
    const vanUploaderFile = {
      file: file,
      name: file.name,
      status: "",
      message: "",
      objectUrl: URL.createObjectURL(file),
    }
    list = [vanUploaderFile]
    emit('success',list)
    close()
  })
}
</script>

<style lang="less" scoped>
.bigContent{
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999999;
  width: 100%;
}
.imgClass{
  width: 100%;
}
.contentMain{
  position: relative;
  height: 100vh;
  background: rgba(0, 0, 0, 0.9);
  .bigImgPD{
    position: absolute;
    bottom: 30px;
    width: 100%;
    padding: 0 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .reset-btn{
    color:#fff;
  }
}
</style>